package cn.shiwei.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CheckloginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        // 返回"pre"表示该过滤器是一个前置过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 返回的int类型数值, 越小其优先级越高
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        // 返回值决定是否要执行run方法(核心方法)
        // 这是一个检查登录状态的过滤器, 在访问私有资源时会判断是否存在token
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login") || requestURI.contains("index")) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 核心方法
        // 判断token对应有无redis缓存(这儿没用redis, 模拟下, 如果token不为空好久放行, 为空就不放心)
        RequestContext currentContext = RequestContext.getCurrentContext();
        String token = currentContext.getRequest().getHeader("token");
        if (StringUtils.isEmpty(token)){
            // 拦截,
            // 拿到拦截对象
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write("尚未登录, 请登录后重试");
            } catch (IOException e) {
                e.printStackTrace();
            }
            currentContext.setSendZuulResponse(false);
        }
        return null;
    }
}
